<template>
  <div>
    <div class="search">
      <input v-model="keywords" class="search-input" type="text" placeholder="输入城市名或拼音" >
    </div>
    <div class="search-content"
         v-show="keywords"
         ref="search"
      >
      <ul>
        <li class="search-item"
          v-for="item of list"
            :key="item.id"
        >{{item.name}}</li>
        <li class="search-item" v-show="hasNoData">未找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keywords: '',
      list: [],
      timer: null
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    keywords () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keywords) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach(value => {
            if (value.spell.indexOf(this.keywords) > -1 || value.name.indexOf(this.keywords) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>

<style lang="stylus" scoped>
  @import "~styles/variables"
  .search
    height: .72rem
    padding: 0 .1rem
    background-color: $themColor
    .search-input
      appearance: none
      outline: 0
      border: 0
      box-sizing: border-box
      width: 100%
      padding: 0 .1rem
      height: .62rem
      line-height: .62rem
      text-align: center
      border-radius: .06rem
      color: #666
  .search-content
    position: absolute
    top: 1.6rem
    left: 0
    right: 0
    bottom: 0
    overflow: hidden
    z-index: 1
    background-color: #eee
    .search-item
      padding: .2rem .24rem
      background-color: #fff
      border-bottom: .02rem solid #ddd
      &:last-child
        border-bottom: none
</style>
